<template>
  <div class="map-wrapper">
    <header>管线绘制选择工具</header>
    <div class="tool-bar">
      <div class="input-item">
        <el-radio @input="changeType" v-model="type" :label="v.value" v-for="v in typeList" :key="v.value">{{ v.name
          }}</el-radio>
        <input id="clear" type="button" class="btn" value="清除" @click="clearAllMaker" />
        <input id="close" type="button" class="btn" value="关闭" @click="closeMouseTools" />
      </div>
    </div>
    <div id="amapContainer"></div>
  </div>
</template>

<script>
import { getAngle } from '@/utils/index.js';
export default {
  name: 'amap3d',
  data () {
    return {
      type: 'marker',
      typeList: [
        { name: '画点', value: 'marker'},
        { name: '画折线', value: 'polyline'},
        { name: '画矩形', value: 'rectangle'},
        { name: '画多边形', value: 'polygon'},
        { name: '画圆', value: 'circle'},
      ],
      makers: [
        { Lng: 116.501415, Lat: 39.926055 },
        { Lng: 116.474605, Lat: 39.946324 },
      ]
    };
  },
  mounted () {
    this.intAmap();
  },
  methods: {
    // 切换覆盖物绘制
    changeType (type) {
      this.clearAllMaker();
      this.drawTypeInt(type, this.mouseTool);
    },
    // 关闭鼠标编辑器
    closeMouseTools () {
      this.mouseTool.close(true);
      this.clearAllMaker();
    },
    // 清空覆盖物
    clearAllMaker () {
      this.map.remove(this.overlays);
      this.overlays = [];
      this.$message.success('覆盖物清空成功');
    },
    // 鼠标事件初始化
    mouseInt (map = this.map) {
      const vm = this;
      const AMap = window?.AMap;
      const mouseTool = new AMap.MouseTool(map);
      //监听draw事件可获取画好的覆盖物
      this.overlays = [];
      mouseTool.on('draw', function (e) {
        vm.overlays.push(e.obj);
      });

      this.mouseTool = mouseTool;

      // 默认绘制点
      vm.drawTypeInt('marker', mouseTool);
    },
    // 根据不同类型绘制不同覆盖物
    drawTypeInt (type, mouseTool) {
      switch (type) {
        case 'marker': {
          mouseTool.marker({
            //同Marker的Option设置
          });
          break;
        }
        case 'polyline': {
          mouseTool.polyline({
            strokeColor: '#80d8ff'
            //同Polyline的Option设置
          });
          break;
        }
        case 'polygon': {
          mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'rectangle': {
          mouseTool.rectangle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'circle': {
          mouseTool.circle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Circle的Option设置
          });
          break;
        }
      }
    },
    drawMap (city = '北京市', LngLats) {
      const AMap = this.AMap;
      const vm = this;
      const opts = {
        subdistrict: 0,
        extensions: 'all',
        level: 'city'
      };
      //利用行政区查询获取边界构建mask路径
      //也可以直接通过经纬度构建mask路径
      const district = new AMap.DistrictSearch(opts);
      district.search(city, function (status, result) {
        const bounds = result.districtList[0].boundaries;
        const mask = [];
        for (let i = 0; i < bounds.length; i += 1) {
          mask.push([bounds[i]]);
        }
        const map = new AMap.Map('amapContainer', {
          mask: mask,
          center: [116.501415, 39.926055],
          disableSocket: true,
          viewMode: '2D',
          showLabel: false,
          labelzIndex: 130,
          pitch: 0,
          zoom: 15,
          // mapStyle: "amap://styles/darkblue",
          // 卫星地图显示
          layers: [
            // new AMap.TileLayer.RoadNet({
            //   //rejectMapMask:true
            // }),
            // new AMap.TileLayer.Satellite()
          ]
        });

        // 添加压力监测点
        (LngLats || []).forEach(v => {
          const position = new AMap.LngLat(v.Lng, v.Lat);
          // 点标记显示内容，HTML要素字符串
          const markerContent = '' +
            `<div class="custom-content-marker zyc-marker-icon">
              <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
              <div class="content">
                <p>1#压力点：1.24 Mpa</p>
                <p>2#压力点：3.02 Mpa</p>
              </div>
            </div>`;

          const maker = new AMap.Marker({
            position: position,
            // 将 html 传给 content
            content: markerContent,
            // 以 icon 的 [center bottom] 为原点
            offset: new AMap.Pixel(-13, -30),
            map: map  // 添加到对应的map地图实例
          });

          maker.on('click', (event) => {
            console.log(event, 'maker地图点击了');
          });
        });

        // 添加管线
        const path = vm.makers.map(v => [v.Lng, v.Lat]);
        const polyline = new AMap.Polyline({
          path: path,
          isOutline: true,
          outlineColor: '#ffeeff',
          borderWeight: 1,
          strokeColor: "red",
          strokeOpacity: 1,
          strokeWeight: 1,
          // 折线样式还支持 'dashed'
          strokeStyle: "solid",
          // strokeStyle是dashed时有效
          strokeDasharray: [10, 5],
          lineJoin: 'round',
          lineCap: 'round',
          zIndex: 50,
        });

        map.add([polyline]);

        // 添加管线名称
        const textLng = (vm.makers[0].Lng + vm.makers[1].Lng) / 2;
        const textLat = (vm.makers[0].Lat + vm.makers[1].Lat) / 2;
        // 根据两个压力点计算管线的方位角
        const textAngle = getAngle(vm.makers[0].Lng, vm.makers[0].Lat, vm.makers[1].Lng, vm.makers[1].Lat);
        const text = new AMap.Text({
          text: 'DN-125',
          anchor: 'center', // 设置文本标记锚点
          draggable: true,
          cursor: 'pointer',
          angle: textAngle + 90, // 必须要+ 90，不然名字和管线是垂直状态
          textData: {
            name: 'sasa',
            age: 11,
            list: [1, 2, 3, 3],
            obj: {
              aa: '12'
            }
          },
          style: {
            'border-radius': '0',
            'background-color': 'white',
            'border-width': 0,
            'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
            'text-align': 'center',
            'font-size': '10px',
            'color': 'blue'
          },
          position: [textLng, textLat]
        });

        text.setMap(map); // 添加管线名称


        polyline.on('click', (event) => {
          console.log(event, 'polyline地图点击了');
        });

        text.on('click', (event) => {
          console.log(event.target.w.textData, 'text地图点击了, 绑定的数据');
        });

        vm.map = map;

        vm.mouseInt(map); // 初始化鼠标事件
      });
    },
    // 地图初始化
    intAmap (callBack) {
      this.AMap = window.AMap;
      this.AMap.plugin(['AMap.MouseTool', 'AMap.PolyEditor', 'AMap.ControlBar', 'AMap.DistrictSearch', 'Map3D', 'AMap.Object3DLayer'], function () {
        //TODO  创建控件并添加
      });

      if (callBack && typeof callBack == 'function') {
        callBack();
      }

      this.drawMap('北京市', this.makers);
    }
  }
};
</script>
<style lang="scss">
#amapContainer {
  .custom-content-marker {
    position: relative;
    width: 25px;
    height: 34px;

    img {
      width: 100%;
      height: 100%;
    }

    .close-btn {
      position: absolute;
      top: -6px;
      right: -8px;
      width: 15px;
      height: 15px;
      font-size: 12px;
      background: #ccc;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 15px;
      box-shadow: -1px 1px 1px rgba(10, 10, 10, 0.2);
    }

    .close-btn:hover {
      background: #666;
    }

    .content {
      position: absolute;
      left: 20px;
      top: 10px;
      height: 100px;
      width: 200px;
      background: rgba(10, 10, 10, 0.7);

      p {
        padding: 5px 10px;
        color: #fff;
        font-size: 14px;
        text-align: left;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.map-wrapper {
  position: relative;
}
header {
  position: relative;
  z-index: 9;
  height: 50px;
  line-height: 50px;
  font-size: 20px;
  font-weight: bolder;
  color: #fff;
  text-align: left;
  padding-left: 15px;
  background: #1890ff;
  box-shadow: 0 2px 4px #333;
}
.tool-bar {
  position: absolute;
  left: 10px;
  top: 60px;
  z-index: 99;
  background: #fff;
  padding: 5px 8px;
  label, .btn {
    margin-right: 10px;
  }
  .input-item {
    display: flex;
    align-items: center;
  }
}

#amapContainer {
  height: calc(100vh - 50px);
  width: 100%;
  margin: 0 auto;
}
</style>